<?php 

/**
 * sfWidgetFormPropelChoice represents a choice widget for a model.
 *
 * @package    symfony
 * @subpackage widget
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfWidgetFormPropelChoice.class.php 12803 2008-11-09 07:26:18Z fabien $
 */
class sfWidgetPropelAjaxBind  extends sfWidgetFormPropelChoice
{
    /**
   * Configures the current widget.
   *
   * Available options:
   *
   *  * url:            The URL to call to get the choices to use (required)
   *  * config:         A JavaScript array that configures the JQuery autocompleter widget
   *  * value_callback: A callback that converts the value before it is displayed
   *
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetForm
   */
    protected function configure($options = array(), $attributes = array())
    {
        $this->addRequiredOption('change_widget');
        $this->addOption('url' , sfContext::getInstance()->getController()->genUrl('@custom_widgets_bind_ajax'));
        $this->addOption('pk' ,'id');
        $this->addOption('fk' , null);

        parent::configure($options, $attributes);
    }

    /**
   * @param  string $name        The element name
   * @param  string $value       The date displayed in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
      public function getChoices(){
          return array();
      }
    
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        $change_widget = preg_replace('/([a-zA-Z0-9_]*)\[.*/','\1['.$this->getOption('change_widget').']' ,$name);

        $fk = $this->getOption('fk');
        $fk = !empty($fk) ? $fk : $this->getOption('change_widget');



        $this_id = $this->generateId($name);

        $change_w_id = $this->generateId($change_widget);

        //die($this_id);

        $add_empty = $this->getOption('add_empty');
        //$content = !empty($add_empty) ? '<option value="" class="empty">'.(is_string($add_empty) ? $add_empty : '').'</option>' : null;

        //return $this->renderContentTag('select' , $content , array('id' => $this_id, 'name' => $name)).
		if(is_array($value)){
			$value = '['.implode(',',$value).']';
		}else{
			$value = "'{$value}'";
		}
		
        return parent::render( $name , $value , $attributes , $errors ).
        sprintf(<<<EOF
<script type="text/javascript">
  jQuery(function($) {
     $('#%s').change(function(){
             this_elem = $('#%s');
             chang_elem = $(this);
             if(!chang_elem.val()){
                //alert(this_elem);
              this_elem.find('option[value!=""]').remove();
              return;
             }
            $.ajax({
                  url: '%s'+$(this).val()
                , beforeSend: function(){
                    $('#%s').addClass('bind-loading');
                }
                ,success : function(data){
                   elm_to_change = $('#%s');
                   elm_to_change.removeClass('bind-loading');
                   elm_to_change.html(data);
                   elm_to_change.find('option:eq(1)').attr('selected','selected');
                   elm_to_change.val({$value});
                   elm_to_change.change();
                }
                ,error    : function(){
                   $('#%s').removeClass('bind-loading');
                }
            });
      });
      if($('#%s').val()){
        $('#%s').change();
      }
    
  });
</script>
EOF
        ,
        $change_w_id
        , $this_id
        , sprintf($this->getOption('url').'?model=%s&pk=%s&peer_method=%s&fk=%s&add_empty=%s&key_method=%s&method=%s&fk_value=',$this->getOption('model'),$this->getOption('pk'),$this->getOption('peer_method'),$fk,$add_empty,$this->getOption('key_method'),$this->getOption('method'))
        , $this_id
        , $this_id
        , $this_id
        , $change_w_id
        , $change_w_id
        );
}

/**
   * Gets the stylesheet paths associated with the widget.
   *
   * @return array An array of stylesheet paths
   */
public function getStylesheets()
{
    //return array('/sfCustomWidgetsPlugin/css/jquery.autocompleter.css' => 'all');
    return array();
}

/**
   * Gets the JavaScript paths associated with the widget.
   *
   * @return array An array of JavaScript paths
   */
public function getJavascripts()
{
    //return array('/sfCustomWidgetsPlugin/js/jquery.autocompleter.js');
    return array();
}
}